import { defineStore } from 'pinia'
import router from '@/router'
import { solveRoutesComponent } from '@/utils/route'
import { getBookListApi } from '@/service/api/user/api'
import { IGetUserMenusResponse } from '@/service/api/user/types'
import { userLoginApi } from '@/service/api/login/api'
import { IUserLoginOption } from '@/service/api/login/types'
import { ElMessage } from 'element-plus'

interface IUserData {
  token: string
  info: {
    name: string
    id: number
    avatar: string
  }
  menus: IGetUserMenusResponse['list']
}
export const useUserStore = defineStore({
  id: 'user',
  state: (): IUserData => ({
    token: '',
    info: {
      name: '',
      id: 0,
      avatar: '',
    },
    menus: [],
  }),
  getters: {},
  actions: {
    setUserInfo(data: IUserData['info']) {
      this.info = data
      localStorage.setItem('user_info', JSON.stringify(data))
    },
    setUserToken(token: string) {
      this.token = token
      localStorage.setItem('user_token', token)
    },
    userLogin(data: IUserLoginOption) {
      userLoginApi(data).then((res) => {
        // 模拟数据
        res.data = {
          token: 'token123',
          info: {
            name: 'wimenlo',
            id: 1,
            avatar: '',
          },
        }
        if (res.data) {
          ElMessage({
            type: 'success',
            message: '登录成功，进入首页',
          })
          this.setUserInfo(res.data.info)
          this.setUserToken(res.data.token)
          router.replace('/dashboard')
        }
      })
    },
    getUserMenu() {
      return getBookListApi().then((res) => {
        if (res.data) {
          // 后台返回数据中，component是路径字符串
          res.data.list = [
            {
              path: 'home',
              name: 'home',
              meta: {
                title: '主页',
              },
              component: '../views/home/index.vue',
            },
            {
              path: 'source_manage',
              name: 'sourceManage',
              meta: {
                title: '资源管理',
                keepAlive: true,
              },
              component: '../views/sourceManage/index.vue',
              children: [
                {
                  path: 'book',
                  name: 'bookManage',
                  meta: {
                    title: '书库',
                    keepAlive: true,
                  },
                  component: '../views/sourceManage/book/index.vue',
                },
                {
                  path: 'book_detail',
                  name: 'bookDetail',
                  meta: {
                    title: '书本详情',
                    hidden: true,
                  },
                  component: '../views/sourceManage/book/detail/index.vue',
                },
                {
                  path: 'game',
                  name: 'gameManage',
                  meta: {
                    title: '游戏库',
                    keepAlive: false,
                  },
                  component: '../views/sourceManage/game/index.vue',
                },
              ],
            },
          ]
          // 将权限路径保存到user store中用作菜单渲染
          this.menus = res.data.list
          // 改为动态加载路径
          const asyncRoutes = solveRoutesComponent(res.data.list)
          // console.log(asyncRoutes)
          // console.log('asyncRoutes loaded')
          router.addRoute({
            path: '/dashboard',
            name: 'dashboard',
            meta: {
              title: '控制台',
            },
            component: () => import('@/views/layout/index.vue'),
            children: [
              ...asyncRoutes,
              {
                path: '401',
                name: '401',
                component: () => import('@/views/error/401.vue'),
              },
              {
                path: '/dashboard/:path(.*)',
                redirect: '/dashboard/401',
              },
            ],
          })
          router.addRoute({
            path: '/:path(.*)',
            redirect: '/404',
          })
        }
      })
    },
  },
})
